package cn.hinglo.baseservice.interceptors;

import cn.hinglo.common.ratelimit.interceptor.AbstractLimitationInterceptor;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author HingLo
 * @createTime: 2018/9/21 17:49
 * @description: 限流拦截器
 */
public class BaseLimitationInterceptors extends AbstractLimitationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws IOException, ServletException {
        HandlerMethod handlerMethod;
        if (handler instanceof HandlerMethod) {
            handlerMethod = (HandlerMethod) handler;
            // 请求头限流,请初始化制定的请求头名称
            String header = "";
            // 用户限流,请传入当前认证的用户唯一标示
            String user = "123";
            initTarget(header, user);
            return run(handlerMethod.getMethod(), response, request);
        }
        // 否则直接通过
        return true;

    }

    @Override
    protected void initTarget(String header, String user) {
        super.setUser(user);
        super.setHeader(header);
    }
}
